function promiseAll(promises) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      return reject("args must be an array");
    }
    let values = [];
    let count = 0;
    let length = promises.length;
    for (let i = 0; i < length; i++) {
      Promise.resolve(promises[i])
        .then((value) => {
          values[i] = value;
          count++;
          if (count === length) {
            resolve(values);
          }
        })
        .catch((err) => {
          reject(err);
        });
    }
  });
}

function promiseRace(promises) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      return reject("arr");
    }
    let len = promises.length;
    for (let i = 0; i < len; i++) {
      Promise.resolve(promises[i])
        .then((value) => {
          resolve(value);
        })
        .catch((reason) => {
          reject(reason);
        });
    }
  });
}

function promiseAllsettled(promises) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      return reject("arr");
    }
    let len = promises.length;
    let current = 0;
    let values = [];
    for (let i = 0; i < len; i++) {
      Promise.resolve(promises[i])
        .then(
          (value) => {
            let a = {
              status: "fulfilled",
              value: value,
            };
            values[i] = a;
            current++;
            if (current === len) {
              return resolve(values);
            }
          },
          (reason) => {
            let a = {
              status: "rejected",
              reason: reason,
            };
            values[i] = a;
            current++;
            if (current === len) {
              return resolve(values);
            }
          }
        )
        .catch((err) => {
          reject(err);
        });
    }
  });
}

function promiseAny(promises) {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) {
      return reject("arr");
    }
    let current = 0;
    let reasons = [];
    let len = promises.length;
    for (let i = 0; i < len; i++) {
      Promise.resolve(promises[i])
        .then(
          (value) => {
            return resolve(value);
          },
          (reason) => {
            reasons[i]=reason;
            current++;
            if (current === len) {
              return reject("a");
            }
          }
        )
        .catch((err) => {
          reject(err);
        });
    }
  });
}

const promise1 = Promise.resolve(3);
const promise2 = Promise.resolve("zzz");
const promise3 = Promise.resolve("zzz");
const promise4 = Promise.resolve("zzz");
const promise5 = Promise.reject("zzz");
const promises = [promise1, promise2, promise3, promise4, promise5];
promiseAll(promises)
  .then((value) => {
    console.log(value);
  })
  .catch((err) => {
    console.log(err);
  });
